﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using AllInOnePluginBL.Helpers;
using PluginDB;

namespace AllInOnePluginBL.SiteScrappers
{
    public class VidicsScrapper : BaseSiteScrapper
    {
        #region Private Members
        private const string DEFAULT_URL = "http://www.vidics.eu";
        private const string MOVIES_URL = "http://www.vidics.eu/Category-Movies/Genre-Any/Letter-Any/ByPopularity/1.htm";
        //private const string TVSHOWS_URL = "http://www.vidics.eu/Category-TvShows/Genre-Any/Letter-Any/LatestFirst/1.htm";

        private const string NAME = "Vidics.eu";
        #endregion

        #region Ctor
        public VidicsScrapper()
            : base(NAME)
        {
        } 
        #endregion

        #region Implementation of IJob
        public override void Execute(int pagesToScan)
        {
            _log.Info(string.Format("Start Executing VidicsScrapper at {0}", DateTime.Now.ToString("r")));

            var lastPageNumber = GetLastPageLink(MOVIES_URL);
            pagesToScan = (pagesToScan == 0 || pagesToScan > lastPageNumber) ? lastPageNumber : pagesToScan;

            for (var i = pagesToScan; i > 0; i--)
            {
                var url = string.Format("{0}/Category-Movies/Genre-Any/Letter-Any/ByPopularity/{1}.htm", DEFAULT_URL, i);
                this.GetMovies(url);
            }

            _log.Info(string.Format("End Executing VidicsScrapper at {0}", DateTime.Now.ToString("r")));
        }
        #endregion

        #region Private Methods
        private void GetMovies(string url)
        {
            try
            {
                string page;
                try
                {
                    page = Utils.GetPage(url, Encoding.UTF8);
                }
                catch (Exception)
                {
                    page = Utils.GetPage(url, Encoding.UTF8);
                }

                const string moviesContainerExpression =
                    "<div class=\"tvshow_img\">.*?<a href=\"(.+?)\" title=\"(.+?)\">.*?<img src=\"(.+?)\" alt=\"(.+?)\" title=\"(.+?)\" class=\"movies_poster\"/>.*?</a>";
                var exp = new Regex(moviesContainerExpression, RegexOptions.Singleline);
                var matches = exp.Matches(page);
                foreach (Match match in matches)
                {
                    try
                    {
                        var moviePageLink = match.Groups[1].Value;
                        var movieImage = DEFAULT_URL + match.Groups[3].Value;
                        var movieTitle = match.Groups[4].Value;

                        if (_pluginDBHandler.IsVideoExists(moviePageLink))
                            continue;

                        var video = FillMovieInfo(movieTitle, moviePageLink, movieImage);

                        if (video.Links.Count == 0)
                        {
                            _log.Warn("{0} Has no links. not saving it", movieTitle);
                            continue;
                        }

                        _pluginDBHandler.AddNewVideo(video);
                    }
                    catch (Exception ex)
                    {
                        _log.ErrorException(string.Format("Error in MyVodParser::Get Movie. moviePageLink:{0}", match.Groups[1].Value), ex);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.ErrorException(string.Format("Error in MyVodParser::GetMovies. url:{0}", url), ex);
            }
        }

        private PluginVideoInfo FillMovieInfo(string movieName, string moviePageLink, string movieImage)
        {
            var pageContent = Utils.GetPage(moviePageLink, Encoding.UTF8);

            var video = new PluginVideoInfo
                            {
                                VideoName = movieName,
                                PluginUrl = moviePageLink,
                                SiteName = NAME,
                                Categories = new List<string>
                                                 {
                                                    "כללי"
                                                 },//GetCategoriesNames(pageContent)),
                                ImageUrl = movieImage,
                                IsHebSub = false
            };

            #region Get Links
            const string LinksPageUrlExp = "url: '/ajax.php?(.+?)'";
            var match = Regex.Match(pageContent, LinksPageUrlExp, RegexOptions.Singleline);
            var fullLinksPage = string.Format("{0}/ajax.php{1}", DEFAULT_URL, match.Groups[1].Value);
            var linksPageContent = Utils.GetPage(fullLinksPage, Encoding.UTF8);

            var links = Utils.GetMovieLinks(linksPageContent);
            foreach (var link in links)
            {
                video.Links.Add(new PluginVideoInfo.Link
                {
                    LinkURL = link,
                    SourceName = GetLinkSource(link)
                });
            }
            return video;
            #endregion
        }

        //private List<string> GetCategoriesNames(string pageContent)
        //{
        //    var categoriesList = new List<string>();
        //    const string expression = "<h5>עוד באותה קטגוריה:(.*?)</h5>";
        //    var match = Regex.Match(pageContent, expression, RegexOptions.Singleline);
        //    if (match.Success)
        //    {
        //        var cleanResult = match.Groups[1].Value.
        //                            Replace("\r", string.Empty).
        //                            Replace("\n", string.Empty).
        //                            Replace(",", ";").Trim();
        //        var categories = cleanResult.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
        //        categoriesList.AddRange(categories.Select(category => category.Trim()));
        //    }

        //    return categoriesList;
        //}

        private string GetLinkSource(string link)
        {
            const string expression = @"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$";
            var match = Regex.Match(link, expression, RegexOptions.Singleline);
            if (match.Success)
            {
                var list = match.Groups[2].Value.Split('.');
                if (list[0] == "www")
                    return list[1];
                return list[0];

            }
            return string.Empty;
        }

        private int GetLastPageLink(string baseUrl)
        {
            try
            {
                var pageContent = Utils.GetPage(baseUrl, Encoding.UTF8);

                const string lastPageExpression = "<table class=\"pagination\".*? &rsaquo; </a></td><td><a href=\"/Category-Movies/Genre-Any/Letter-Any/ByPopularity/(.+?).htm\"> &rsaquo;&rsaquo; </a>";
                var exp = new Regex(lastPageExpression, RegexOptions.Singleline);
                var match = exp.Match(pageContent);
                if (match.Success)
                {
                    return int.Parse(match.Groups[1].Value);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in GetLastPageLink: {0}", ex.Message);
            }

            return 0;
        }
        #endregion
    }
}
